import axios, { AxiosRequestConfig } from 'axios'
import { getToken, removeToken } from '@/utils/auth'
import router from '@/router/index'

const request = axios.create({
  baseURL: import.meta.env.VITE_SERVICE_BASE_URL, // 基础路径
  timeout: 6000 // 超时时间
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    config.url = config.url?.trim()
    const token = getToken()
    if (token) {
      config.headers = {
        'Authorization': `Bearer ${token}`
      }
    }
    //get请求映射参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?';
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof (value) !== "undefined") {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              if (value[key] !== null && typeof (value[key]) !== 'undefined') {
                let params = propName + '[' + key + ']';
                let subPart = encodeURIComponent(params) + '=';
                url += subPart + encodeURIComponent(value[key]) + '&';
              }
            }
          } else {
            url += part + encodeURIComponent(value) + "&";
          }
        }
      }
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response
  },
  err => {
    if (err.response === undefined) {
      ElMessage.error("服务器异常")
    } else {
      const { status, message } = err.response.data;
      console.log(router.currentRoute.value.fullPath)
      if (status === 401) {
        ElMessage.error(message)
        removeToken()
        console.log(router.currentRoute.value.fullPath)
        location.href = '/admin/login';
      } else {
        ElMessage.error(status + " " + message)
      }
    }
    return Promise.reject(err)
  }
)

// 将request作为函数导出
// 指定res.data.data的数据类型（后端返回的）为T
export default async <T = any>(config: AxiosRequestConfig) => {
  const res = await request(config)
  return (res.data.data || res.data) as T
}
